<template>
  <div class="product-management-page">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <h1 style="margin: 0">商品管理</h1>
      </div>

      <!-- Loading indicator -->
      <el-skeleton v-if="isLoading" :rows="6" animated />

      <!-- Empty state -->
      <el-empty v-else-if="products.length === 0" description="暂无商品" />

      <!-- Product list -->
      <div v-else>
        <el-row :gutter="20">
          <el-col v-for="product in products" :key="product.id" :xs="24" :sm="12" :md="8" :lg="6">
            <el-card class="product-card" :body-style="{ padding: '15px' }">
              <div class="product-image-container">
                <el-image
                    :src="product.image_url"
                    fit="contain"
                    class="product-image"
                    :preview-src-list="[product.image_url]"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>

              <div class="product-info">
                <p class="product-name">{{ product.name }}</p>
                <p class="product-price">￥{{ product.price.toFixed(2) }}</p>
                <p class="product-stock">库存: {{ product.stock }}</p>
                <p class="product-status">
                  <el-tag :type="product.is_active ? 'success' : 'danger'">
                    {{ product.is_active ? '上架' : '下架' }}
                  </el-tag>
                </p>
              </div>

              <div class="product-actions">
                <el-button
                    size="small"
                    type="primary"
                    @click="editProduct(product)"
                >
                  编辑
                </el-button>
                <el-button
                    size="small"
                    :type="product.is_active ? 'danger' : 'success'"
                    @click="toggleProductStatus(product)"
                >
                  {{ product.is_active ? '下架' : '上架' }}
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- Edit dialog -->
      <el-dialog
          :title="'编辑商品'"
          :visible.sync="isEditing"
          width="50%"
          :close-on-click-modal="false"
      >
        <el-form :model="currentProduct" label-width="100px">
          <el-form-item label="商品名称" prop="name">
            <el-input v-model="currentProduct.name" />
          </el-form-item>
          <el-form-item label="价格" prop="price">
            <el-input-number
                v-model="currentProduct.price"
                :min="0"
                :step="0.01"
                :precision="2"
            />
          </el-form-item>
          <el-form-item label="库存" prop="stock">
            <el-input-number v-model="currentProduct.stock" :min="0" />
          </el-form-item>
          <el-form-item label="商品图片" prop="image_url">
            <el-input v-model="currentProduct.image_url" />
          </el-form-item>
        </el-form>

        <span slot="footer" class="dialog-footer">
          <el-button @click="cancelEdit">取 消</el-button>
          <el-button type="primary" @click="saveProduct">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>

    <div class="back-button-container">
      <el-button
          type="info"
          @click="goBack"
          icon="el-icon-back"
      >
        返回商家首页
      </el-button>
    </div>
  </div>
</template>

<script lang="ts">
import axios from 'axios';
import { defineComponent, ref, reactive, onMounted } from 'vue';
import {ElMessage} from "element-plus";

export default defineComponent({
  name: 'ProductManagement',
  setup() {
    const products = ref<Array<any>>([]);
    const isLoading = ref(true);
    const isEditing = ref(false);
    const currentProduct = reactive<any>({});
    const userId = sessionStorage.getItem('userId');

    const goBack = () => {
      window.location.href = '/seller';
    };

    const loadProducts = async () => {
      try {
        const response = await axios.get(`/api/product/seller/${userId}`);
        products.value = response.data;
      } catch (error) {
        console.error('加载商品失败:', error);
        ElMessage.error('加载商品失败，请稍后重试。');
      } finally {
        isLoading.value = false;
      }
    };

    const editProduct = (product: any) => {
      Object.assign(currentProduct, product);
      isEditing.value = true;
    };

    const saveProduct = async () => {
      try {
        const response = await axios.put(`/api/product/${currentProduct.id}`, currentProduct);
        if (response.status === 200) {
          ElMessage.success('商品信息已更新');
          isEditing.value = false;
          await loadProducts();
        }
      } catch (error) {
        console.error('更新商品失败:', error);
        ElMessage.error('更新商品失败，请稍后重试。');
      }
    };

    const cancelEdit = () => {
      isEditing.value = false;
    };

    const toggleProductStatus = async (product: any) => {
      try {
        const newStatus = !product.is_active;
        const response = await axios.patch(`/api/product/${product.id}/status?isActive=${newStatus}`);
        if (response.status === 200) {
          ElMessage.success(`商品已${newStatus ? '上架' : '下架'}`);
          await loadProducts();
        }
      } catch (error) {
        console.error('更新商品状态失败:', error);
        ElMessage.error('操作失败，请稍后重试。');
      }
    };

    onMounted(() => {
      loadProducts();
    });

    return {
      products,
      isLoading,
      isEditing,
      currentProduct,
      loadProducts,
      editProduct,
      saveProduct,
      cancelEdit,
      toggleProductStatus,
      goBack
    };
  },
});
</script>

<style scoped>
.product-management-page {
  padding: 20px;
  max-width: 1400px;
  margin: 0 auto;
}

.box-card {
  margin-bottom: 20px;
}

.product-card {
  margin-bottom: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
}

.product-image-container {
  height: 180px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 15px;
}

.product-image {
  max-height: 100%;
  max-width: 100%;
}

.product-info {
  flex-grow: 1;
  margin-bottom: 15px;
}

.product-name {
  font-size: 16px;
  font-weight: bold;
  margin-bottom: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.product-price {
  color: #f56c6c;
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 8px;
}

.product-stock {
  color: #666;
  margin-bottom: 8px;
}

.product-actions {
  display: flex;
  justify-content: space-between;
}

.back-button-container {
  text-align: center;
  margin-top: 20px;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}
</style>